﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Packaging;
using System.Text.RegularExpressions;
using Quexcel.OpenXML.Excel.Factory;
using Quexcel.OpenXML.Transaction;
using Quexcel.OpenXML.Interfaces;
using System.Xml;

namespace Quexcel.OpenXML.Excel.SharedString
{
    internal class SharedStringData
    {
        private PackagePart DocumentPart { get; set; }

        private ExcelTransaction transaction;
        private Quexcel.OpenXML.Excel.Workbook.Workbook workbook;
        private string worksheetName;
        private ISharedStringReader sharedStringReader;
        private static ISharedStringWriter sharedStringWriter;

        internal SharedStringData(ExcelTransaction transaction, Quexcel.OpenXML.Excel.Workbook.Workbook workbook, PackagePart docPart)
        {
            this.DocumentPart = docPart;
            this.workbook = workbook;
            worksheetName = (new Regex("(?<name>[^/]+).xml")).Match(docPart.Uri.ToString()).Result("${name}");
        }

        string WorksheetName { get { return worksheetName; } }
        Quexcel.OpenXML.Excel.Workbook.Workbook Workbook { get { return workbook; } }
        internal XmlNamespaceManager NameSpaceManager
        {
            get { return workbook.NameSpaceManager; }
        }

        public ISharedStringReader GetReader()
        {
            if (sharedStringReader == null)
                sharedStringReader = ReaderWriterBuilder.GetSharedStringReader(DocumentPart, NameSpaceManager);
            return sharedStringReader;
        }

        public ISharedStringWriter GetWriter()
        {
            if (sharedStringWriter == null)
                sharedStringWriter = ReaderWriterBuilder.GetSharedStringWriter(DocumentPart, NameSpaceManager);
            return sharedStringWriter;
        }

        public bool HasWriter()
        {
            return sharedStringWriter != null;
        }

        public bool HasReader()
        {
            return sharedStringReader != null;
        }
    }
}
